﻿using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebDAVSharp.Server.Exceptions;
using WebDAVSharp.Server.Stores;
using WebDAVSharp.Server.Stores.DiskStore;

namespace AzureStorageLight
{
    public class BackupWebDavStoreCollection : BackupWebDavStoreItem, IWebDavStoreCollection
    {
        public BackupWebDavStoreCollection(BackupWebDavStoreCollection parentCollection, string path)
            : base(parentCollection, null, path)
        {

        }

        public IEnumerable<IWebDavStoreItem> Items
        {
            get
            {
                EnsureItems();
                return _items;
            }
        }

        private void EnsureItems()
        {
            if (_items == null)
            {
                _items = new List<BackupWebDavStoreItem>();
                _blobs = Service.ListBackup(ItemPath, true);
                foreach (var f in _blobs.OfType<CloudBlockBlob>())
                {
                    _items.Add(new BackupWebDavStoreDocument(this, f));
                }
                foreach (var d in _blobs.OfType<CloudBlobDirectory>())
                {
                    _items.Add(new BackupWebDavStoreCollection(this, d.Prefix));
                }
            }
        }

        private List<BackupWebDavStoreItem> _items;
        private List<IListBlobItem> _blobs;

        public IWebDavStoreItem CopyItemHere(IWebDavStoreItem source, string destinationName, bool includeContent)
        {
            throw new WebDavUnauthorizedException();
        }

        public IWebDavStoreCollection CreateCollection(string name)
        {
            throw new WebDavUnauthorizedException();
        }

        public IWebDavStoreDocument CreateDocument(string name)
        {
            throw new WebDavUnauthorizedException();
        }

        public void Delete(IWebDavStoreItem item)
        {
            throw new WebDavUnauthorizedException();
        }

        public IWebDavStoreItem GetItemByName(string name)
        {
            foreach (var item in Items.Cast<BackupWebDavStoreItem>())
            {
                if (StorageItemUtil.GetFileName(item.Name) == name)
                {
                    return item;
                }
            }
            return null;
        }

        public IWebDavStoreItem MoveItemHere(IWebDavStoreItem source, string destinationName)
        {
            throw new WebDavUnauthorizedException();
        }

    }
}
